package com.ymx.darling.executor.proxy;

import com.ymx.darling.executor.Executor;
import com.ymx.darling.intercept.ExecutorInterceptor;
import com.ymx.darling.intercept.InterceptManager;
import com.ymx.darling.intercept.Invocation;
import com.ymx.darling.util.ExceptionUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * Executor代理执行器
 * 用于拦截executor执行的方法进入用户自定义的插件拦截
 * @author 爱Java的小于
 */
public class ExecutorInvocationHandler implements InvocationHandler {
    private final Executor target;
    private final ExecutorInterceptor interceptor;

    public ExecutorInvocationHandler(Executor executor, ExecutorInterceptor executorInterceptor) {
        this.target = executor;
        this.interceptor = executorInterceptor;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Invocation invocation = new Invocation(this.target, method, args);
        // 判断调用的是待拦截的方法
        if (InterceptManager.isExecutorInterceptMethod(method.getName())) {
            try {
                return interceptor.intercept(invocation);
            } catch (Throwable throwable) {
                throw ExceptionUtil.unwrapThrowable(throwable);
            }
        }
        // 不走拦截处理直接调用目标执行器执行
        return method.invoke(this.target, args);
    }
}
